package com.wwinsoft.framework.web.system.Taglib;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wwinsoft.framework.entity.system.Code;
import com.wwinsoft.framework.service.system.CodeManager;

public class CodeTag extends TagSupport {

    private String codeType;
    private String codeValue;

    private String table;
    private String codeColumn;
    private String valueColumn;
    private String where;

    public int doStartTag() throws JspException {
        ServletContext sc = pageContext.getServletContext();
        JspWriter out = pageContext.getOut();
        try {
            if ((StringUtils.isEmpty(codeType) && StringUtils.isEmpty(table)) ||  StringUtils.isEmpty(codeValue)) {
                out.print(codeValue);
                return super.doStartTag();
            }
            WebApplicationContext webAppCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
            CodeManager codeManager = (CodeManager) webAppCtx.getBean("codeManager");
            Code code;
            if(StringUtils.isNotEmpty(codeType)){
                code = codeManager.getCodeByTypeAndCodeValue(codeType, codeValue);
            }else{
                code = codeManager.getCodeByTable(table, codeColumn, valueColumn, where, codeValue);
            }
            if (code == null) {
                out.print(codeValue);
            } else {
                out.print(code.getCode());
            }
        } catch (Exception e) {
            throw new JspException(e);
        }
        return super.doStartTag();
    }

    public void setCodeType(String codeType) {
        this.codeType = codeType;
    }

    public void setCodeValue(String codeValue) throws JspException {
        this.codeValue = (String) ExpressionEvaluatorManager.evaluate("codeValue", codeValue, String.class, this,
                                                                      pageContext);
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }

    public String getCodeColumn() {
        return codeColumn;
    }

    public void setCodeColumn(String codeColumn) {
        this.codeColumn = codeColumn;
    }

    public String getValueColumn() {
        return valueColumn;
    }

    public void setValueColumn(String valueColumn) {
        this.valueColumn = valueColumn;
    }

    public String getWhere() {
        return where;
    }

    public void setWhere(String where) {
        this.where = where;
    }
}